<div id="mdViewer">
	<div id="mdViewerToolBar" style="height:100px;">
	     <button id="btnMdExitEdit" class="btn btn-default" type="button" onclick="MdViewer.exitEdit()" style="display:none">退出编辑
	     </button>
	     <button id="btnMdSaveWiki" class="btn btn-default" type="button" onclick="MdViewer.saveWiki()" style="display:none">保存
	     </button>
	</div>
	<div class="mdViewerContent" style="min-height: 600px;">
		<div id="mdPlayer">
		</div>
	</div>
</div>

<script type="text/javascript">
var MdViewer = (function () {
	var docInfo = {};
	
	var docText = "";
	var tmpSavedDocText = "";
	
	var md;	//mdeditor对象
  	//自动保存定时器
  	var autoSaveTimer;
  	var timerState = 0;
  	var isOnLoadTriggerChange = false;

  	
	function mdViewerPageInit(Input_doc, Input_docText, Input_tmpSavedDocText)
	{
		console.log("mdViewerPageInit InputDoc:", Input_doc);
		docInfo = Input_doc;		
		docText = Input_docText;
		tmpSavedDocText = Input_tmpSavedDocText;
		loadmd(docText, false);
	}

  	function editorInit(content, edit)
  	{
  		console.log("MdViewer editorInit edit:" + edit);

  		var params = {
           width: "100%",
           height: $(document).height()-70,
           path : 'static/markdown/lib/',
           markdown : "",	//markdown的内容默认务必是空，否则会出现当文件内容是空的时候显示默认内容
           toolbar  : false,             // 关闭工具栏
           codeFold : true,
           searchReplace : true,
           saveHTMLToTextarea : true,      // 保存 HTML 到 Textarea
           htmlDecode : "style,script,iframe|on*",            // 开启 HTML 标签解析，为了安全性，默认不开启
           emoji : true,
           taskList : true,
           tocm: true,          			// Using [TOCM]
           tex : true,                      // 开启科学公式 TeX 语言支持，默认关闭
           //previewCodeHighlight : false,  // 关闭预览窗口的代码高亮，默认开启
           flowChart : true,
           sequenceDiagram : true,
           //dialogLockScreen : false,      // 设置弹出层对话框不锁屏，全局通用，默认为 true
           //dialogShowMask : false,     // 设置弹出层对话框显示透明遮罩层，全局通用，默认为 true
           //dialogDraggable : false,    // 设置弹出层对话框不可拖动，全局通用，默认为 true
           dialogMaskOpacity : 0.2,    // 设置透明遮罩层的透明度，全局通用，默认值为 0.1
           dialogMaskBgColor : "#000", // 设置透明遮罩层的背景颜色，全局通用，默认为 #fff
           imageUpload : true,
           imageFormats : ["jpg","JPG", "jpeg","JPEG","gif","GIF","png", "PNG","bmp","BMP", "webp","WEBP",],
           imageUploadURL : "/DocSystem/Doc/uploadMarkdownPic.do?docId="+docInfo.docId + "&path=" + docInfo.path + "&name=" + docInfo.name,
           onchange : function () {
               console.log("MdViewer onchange docInfo.edit:" + docInfo.edit);                  
           },
           onpreviewing : function () {
               console.log("MdViewer onpreviewing docInfo.edit:" + docInfo.edit);
               exitEditWiki();
           },
           onpreviewed :function () {
               console.log("MdViewer onpreviewed docInfo.edit:" + docInfo.edit);
               lockAndEditWiki();
           },
           onload : function () {
               console.log("MdViewer onload docInfo.edit:" + docInfo.edit + " edit:" + edit);	//这是markdown初始化完毕的回调（此时才可以访问makdown的接口）
	    		   this.previewing(); 		  //加载成默认是预览
	    		   this.setMarkdown(content); //内容需要在onload的时候进行加载，会触发onchange事件
	    		   isOnLoadTriggerChange = true;
	    		   if(!edit || edit == false)
    		   {
	    			   console.log("MdViewer onload edit is false");
    		   }
	    		   else
	    		   {
	    			   console.log("MdViewer onload edit is true");
	    			   lockAndEditWiki();
    		   }
           },
           onresize: function(){
        	   console.log("MdViewer onresize");
           }
   		};
   		
   		md = editormd("mdPlayer",params);
  	}
    
	function editorLoadmd(content) 
	{
		console.log("MdViewer editorLoadmd() docInfo.edit:" + docInfo.edit);
		md.setMarkdown(content);
    }
    
    function loadmd(content, edit)
    {
		if(!content)
		{
			content = "";
		}
		
		//console.log("loadmd content:", content);				
		
		if(md)
		{
  			editorLoadmd(content);               				
		}
		else
		{
			editorInit(content, edit);	
		}
    }
	      		
	function editorSwitch(edit)
	{
		console.log("MdViewer editorSwitch() edit:"+edit + " docInfo.edit:" + docInfo.edit);
		
		docInfo.edit = edit;
		
		if(!md)
   		{
			showErrorMessage("请先初始化Markdown编辑器");
   			return;
   		}
   		
		if(edit == false)
    	{
    		md.previewing();
    	}
    	else
    	{
    		md.previewed();
    	}
	}
	
	function startAutoTmpSaver()
	{ 
		console.log("MdViewer.startAutoTmpSaver timerState:" + timerState);
		if(timerState == 0)
		{
			timerState = 1;
			autoSaveTimer = setInterval(function () {
	        	var newContent = getMarkdown();
	        	if(!tmpSavedDocText)
	        	{
	        		tmpSavedDocText = "";
	        	}
	        	
				if(tmpSavedDocText != newContent)
	    		{
	    			console.log("autoTmpSaveWiki");
	    			tmpSaveDoc(docInfo.docId, newContent);
	    			tmpSavedDocText = newContent;
	    		}
	    	},20000);
	    }
	}

	function stopAutoTmpSaver(){
		console.log("MdViewer.stopAutoTmpSaver timerState:" + timerState);
		if(timerState == 1)
		{
			timerState = 0;
			clearInterval(autoSaveTimer);
		}
	}
	
    //文件临时保存操作
    function tmpSaveDoc(node, content){
		$.ajax({
            url : "/DocSystem/Doc/tmpSaveDocContent.do",
            type : "post",
            dataType : "json",
            data : {
            	reposId: gReposInfo.id,
                docId : node.docId,
                pid: node.pid,
                path: node.path,
                name: node.name,
                content : content,
                docType : 1, //realDoc
            },
            success : function (ret) {
                if( "ok" == ret.status ){
                    console.log("临时保存成功 :" , (new Date()).toLocaleDateString());
                    bootstrapQ.msg({
								msg : "临时保存成功 :" + (new Date()).toLocaleDateString(),
								type : 'success',
								time : 1000,
					});
                }else {
                    //bootstrapQ.alert("临时保存失败:"+ret.msgInfo);
                    bootstrapQ.msg({
						msg : "临时保存失败 :" + +ret.msgInfo,
						type : 'danger',
						time : 1000,
					});
                }
            },
            error : function () {
                //bootstrapQ.alert("临时保存异常");
                bootstrapQ.msg({
					msg : "临时保存失败 :服务器异常",
					type : 'danger',
					time : 1000,
				});
            }
        });

    }
    
    //文件临时Delete操作
    function deleteTmpSavedContent(node)
    {	
        $.ajax({
            url : "/DocSystem/Doc/deleteTmpSavedDocContent.do",
            type : "post",
            dataType : "json",
            data : {
            	reposId: gReposInfo.id,
                docId : node.docId,
                pid: node.pid,
                path: node.path,
                name: node.name,
                docType: 1,
            },
            success : function (ret) {
                if( "ok" == ret.status ){
                    console.log("删除临时保存内容成功 :" , (new Date()).toLocaleDateString());
                    bootstrapQ.msg({
								msg : "删除临时保存内容成功 :" + (new Date()).toLocaleDateString(),
								type : 'success',
								time : 1000,
					});
                }else {
                    //bootstrapQ.alert("临时保存失败:"+ret.msgInfo);
                    bootstrapQ.msg({
						msg : "删除临时保存内容失败 :" + +ret.msgInfo,
						type : 'danger',
						time : 1000,
					});
                }
            },
            error : function () {
                //bootstrapQ.alert("临时保存异常");
                bootstrapQ.msg({
					msg : "删除临时保存内容失败 :服务器异常",
					type : 'danger',
					time : 1000,
				});
            }
        });
    }
    
	//进入文件编辑状态
    function editWiki(){
    	console.log("editWiki()  docInfo.docId:" + docInfo.docId + " docInfo.edit:" + docInfo.edit);
	    if(docInfo.edit == true)
	    {
	    	return;
	    }

	    docInfo.edit = true;
    	MdViewer.editorSwitch(true);
    	MdViewer.loadmd(docText);
    	WikiEditBtnCtrl(true);
        
        //start the autoTmpSaver
	    MdViewer.startAutoTmpSaver();
	    
		if(tmpSavedDocText && tmpSavedDocText != docText)
		{
			bootstrapQ.confirm({
				id: "loadContentConfirm",
				title: "加载确认",
				msg : "上次有未保存的编辑内容，是否加载？",
				},function () {
			    	//alert("点击了确定");
			        MdViewer.loadmd(tmpSavedDocText);
			    	return true;   
			 	},function (){
			 		//alert("点击了取消");
			        tmpSavedDocText = docText;
			        MdViewer.deleteTmpSavedContent(docInfo.docId);
			        return true;
			 	});
		}
    }
	
	
	function WikiEditBtnCtrl(edit)
	{
		 if(edit == true)
	   	 {
		    $("#btnMdExitEdit").show();
	      	$("#btnMdSaveWiki").show();  
	     }
	     else
	     {
		    $("#btnMdExitEdit").hide();
	      	$("#btnMdSaveWiki").hide();
	     }
	}
	
    function exitEditWiki() {
      	console.log("exitEditWiki()  docInfo.docId:" + docInfo.docId + " docInfo.edit:" + docInfo.edit);
	    if(docInfo.edit == false)
	    {
	    	return;
	    }

	    docInfo.edit = false;
      	editorSwitch(false);
      	loadmd(docText);
	    WikiEditBtnCtrl(false);
	        
		//Stop autoSaver
		MdViewer.stopAutoTmpSaver();
    }
    
    //将编辑中的文件保存到后台
    function saveWiki() {
    	console.log("saveWiki");
    	var newContent = getMarkdown();
    	if(docText != newContent)
    	{
    		saveDoc(newContent);
    	}
    }
    
	//锁定文件并进入编辑状态
	function lockAndEditWiki()
	{
		console.log("lockAndEditWiki()");
		if(!docInfo.docId || docInfo.docId == 0)
		{
			showErrorMessage("请选择文件!");
			return;
		}

		$.ajax({
			url : "/DocSystem/Doc/lockDoc.do",
			type : "post",
			dataType : "json",
			data : {
				lockType : 1, //LockType: Online Edit
				reposId : gReposInfo.id, 
				docId : docInfo.docId,
				path: docInfo.path,
				name: docInfo.name,
				docType: docInfo.contentType,
			},
			success : function (ret) {
				if( "ok" == ret.status)
				{
					console.log("lockAndEditWiki() ret.data",ret.data);
					$("[dataId='"+ docInfo.docId +"']").children("div:first-child").css("color","red");
					editWiki();
				    return;
 				}
				else
				{
					showErrorMessage("lockDoc Error:" + ret.msgInfo);
					return;
				}
			},
			error : function () 
			{
				showErrorMessage("lockDoc 异常");
				return;
			}
		});
	}
	
	function getMarkdown()
	{
		var content = md.getMarkdown();
    	if(!content)
    	{
    		content = "";
    	}
    	return content;
	}

	//退出文件编辑状态
    function exitEdit() 
	{
    	console.log("exitEdit docInfo.docId:" + docInfo.docId);	
    	if(docInfo.edit == false)
    	{
    		return;
    	}
    	
    	var newContent = getMarkdown();
    	if(!docText)
    	{
    		docText = "";
    	}
    	if(docText != newContent)
    	{
    		//console.log("exitEdit docText:" + docText);	
    		//console.log("exitEdit newContent:" + newContent);	
    		qiao.bs.confirm({
  	 	    		id: 'saveDocConfirm',
  	 	    		msg: "修改未保存，是否保存？",
  	 	    		close: false,		
  	 	    		okbtn: "保存",
  	 	    		qubtn: "直接退出",
  	 	    	},function () {
  	 	    	    saveWikiAndExit();
  	  	 			return true;
  	 			},function(){
  	 				unlockAndExitEditWiki();
  	 				return true;
  	 		});
  	 	}
  	 	else
  	 	{
    		unlockAndExitEditWiki();
    	}
	}
    
	//解锁文件并退出编辑
	function unlockAndExitEditWiki()
	{
		console.log("unlockAndExitEditWiki()  docInfo.docId:" + docInfo.docId);
		if(!docInfo.docId || docInfo.docId == 0)
		{
			showErrorMessage("文件不存在");
			exitEditWiki();
			return;
		}
		
		$.ajax({
			url : "/DocSystem/Doc/unlockDoc.do",
			type : "post",
			dataType : "json",
			data : {
				lockType : 1, //unlock the doc
				reposId : gReposInfo.id, 
				docId : docInfo.docId,
				path: docInfo.path,
				name: docInfo.name,
				docType: docInfo.contentType,
			},
			success : function (ret) {
				if( "ok" == ret.status)
				{
					console.log("unlockAndExitEditWiki() ret:" + ret.data);
					$("[dataId='"+ docInfo.docId +"']").children("div:first-child").css("color","black");
					exitEditWiki();
					return;
 				}
				else
				{
					showErrorMessage("unlockAndExitEditWiki() unlockDoc Error:" + ret.msgInfo);
					return;
				}
			},
			error : function () 
			{
				showErrorMessage("unlockAndExitEditWiki() unlockDoc 异常");
				return;
			}
		});
	}
	
    //将编辑中的文件保存到后台
    function saveWikiAndExit() 
    {
    	console.log("saveWikiAndExit  gDoc:" + docInfo.docId, newNode);
    	var newContent = getMarkdown();
    	if(docText != newContent)
    	{
    		saveDoc(newContent, unlockAndExitEditWiki);
    	}
    	else
    	{
    		unlockAndExitEditWiki();
    	}
    }
    
    function saveDoc(content, callback)
	{
		console.log("saveDoc docInfo.docId:" + docInfo.docId);
		$.ajax({
            url : "/DocSystem/Doc/updateDocContent.do",
            type : "post",
            dataType : "json",
            data : {
                reposId: gReposInfo.id,
            	docId : docInfo.docId,
            	path: docInfo.path,
                name: docInfo.name,
            	content : content,
            	docType: 1,
            },
            success : function (ret) {
                if( "ok" == ret.status ){
                    console.log("保存成功 : " , (new Date()).toLocaleDateString());
					docText = content;

                    bootstrapQ.msg({
								msg : "保存成功 :" + (new Date()).toLocaleDateString(),
								type : 'success',
								time : 1000,
					});
					//回调
					callback && callback();
				}else {
                    bootstrapQ.alert("保存失败:"+ret.msgInfo);
                }
            },
            error : function () {
                bootstrapQ.alert("保存失败:服务器异常");
            }
        });
    }
    
    function resize()
   	{
		if(!md)
		{
			return;
		}
		md.resize();
   	}
    
	//开放给外部的调用接口
    return {
        mdViewerPageInit: function(docInfo, docText, tmpSavedDocText){
        	mdViewerPageInit(docInfo, docText, tmpSavedDocText);
        },
    	resize: function(){
			resize();
        },
        loadmd: function(content, edit){
           loadmd(content, edit);
        },
        editWiki: function(){
        	editWiki();
        },
        exitEdit: function(newNode){
        	exitEdit(newNode);
        },
        saveWiki: function(){
        	saveWiki();
        },
        editorSwitch: function(edit){
        	editorSwitch(edit);
        },
        startAutoTmpSaver: function(){
        	startAutoTmpSaver();
        },
        stopAutoTmpSaver: function(){
        	stopAutoTmpSaver();
        },
        
        deleteTmpSavedContent: function(docId){
        	deleteTmpSavedContent(docId);
        },        
    };
})();

</script>